﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;

namespace LoomDataEmulator.Core
{
    public class Scheduler : IScheduler, IDisposable
    {
        private List<IScheduledTask> _scheduledTasks;
        private Timer _timer;

        #region IScheduler Members
        public Scheduler(Timer timer)
        {
            if(timer == null)
            {
                timer = new Timer();
                timer.Interval = 60000;
                Timer = timer;
            }
            else
            {
                if (timer.Interval < 60000)
                    timer.Interval = 60000;
                this.Timer = timer;    
            }
            

            SchedulerStart();
        }

        public void RegisterNewTask(IScheduledTask newTask)
        {
            _scheduledTasks.Add(newTask);
            _timer.Elapsed += new ElapsedEventHandler(newTask.OnElapsedTime);
            newTask.Registered = true;
        }

        public System.Timers.Timer Timer
        {
            get { return _timer; }
            set { _timer = value; }
        }

        public List<IScheduledTask> ScheduledTasks
        {
            get { return _scheduledTasks; }
            set { _scheduledTasks = value; }
        }

        public void SchedulerStart()
        {
            if (_scheduledTasks == null)
                _scheduledTasks = new List<IScheduledTask>();

            this.Timer.Enabled = true;

            foreach (IScheduledTask scheduledTask in ScheduledTasks)
            {
                if (scheduledTask.Registered == false)
                    this.Timer.Elapsed += new ElapsedEventHandler(scheduledTask.OnElapsedTime);
            }
        }

        public void SchedulerStop()
        {
            if (ScheduledTasks != null)
            {
                foreach (IScheduledTask scheduledTask in ScheduledTasks)
                {
                    if (scheduledTask != null)
                    {
                        this.Timer.Elapsed -= scheduledTask.OnElapsedTime;
                        scheduledTask.Registered = false;
                    }
                }

                this.Timer.Enabled = false;
            }
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            SchedulerStop();
        }

        #endregion
    }
}
